<template>
  <el-drawer
    v-model="visible"
    title="申请详情"
    size="600px"
    :destroy-on-close="false"
  >
    <div class="detail-content" v-if="applicationData">
      <!-- 基本信息 -->
      <div class="section">
        <h3 class="section-title">基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请ID">{{ applicationData.applicationId }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ applicationData.userName }}</el-descriptions-item>
          <el-descriptions-item label="申请类型">
            <el-tag :type="getApplicationTypeTag(applicationData.applicationType)">
              {{ getApplicationTypeLabel(applicationData.applicationType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="教室类型">
            <el-tag type="info">{{ getClassroomTypeLabel(applicationData.classroomType) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预计人数">{{ applicationData.expectedPeople }}人</el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getStatusTag(applicationData.status)">
              {{ getStatusLabel(applicationData.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 时间信息 -->
      <div class="section">
        <h3 class="section-title">时间信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请日期">{{ formatDate(applicationData.applyDate) }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDateTime(applicationData.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="使用日期">{{ formatDate(applicationData.applyDate) }}</el-descriptions-item>
          <el-descriptions-item label="使用时间">{{ applicationData.startTime }} - {{ applicationData.endTime }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 用途和设备需求 -->
      <div class="section">
        <h3 class="section-title">用途和设备需求</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用途">{{ applicationData.purpose }}</el-descriptions-item>
          <el-descriptions-item label="设备需求">
            <el-tag 
              v-for="equipment in equipmentList" 
              :key="equipment" 
              size="small" 
              style="margin-right: 8px; margin-bottom: 4px;"
            >
              {{ equipment }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 审批信息 -->
      <div class="section" v-if="applicationData.status !== 'PENDING'">
        <h3 class="section-title">审批信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审批人">{{ applicationData.approverName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审批时间">{{ formatDateTime(applicationData.approveTime || '') }}</el-descriptions-item>
          <el-descriptions-item label="审批结果">
            <el-tag :type="applicationData.status === 'APPROVED' ? 'success' : 'danger'">
              {{ applicationData.status === 'APPROVED' ? '通过' : '拒绝' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审批意见">{{ applicationData.approveComment || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 分配信息 -->
      <div class="section" v-if="applicationData.status === 'ALLOCATED' || applicationData.status === 'COMPLETED'">
        <h3 class="section-title">分配信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="分配人">{{ applicationData.allocatorName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="分配时间">{{ formatDateTime(applicationData.allocateTime || '') }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 分配的教室列表 -->
        <div class="allocated-classrooms">
          <h4>分配的教室</h4>
          <el-table :data="allocatedClassrooms" style="width: 100%">
            <el-table-column prop="classroomCode" label="教室编号" width="120" />
            <el-table-column prop="capacity" label="容量" width="80" />
            <el-table-column prop="equipment" label="设备" min-width="150" />
            <el-table-column prop="location" label="位置" min-width="120" />
          </el-table>
        </div>
      </div>

      <!-- 操作记录 -->
      <div class="section">
        <h3 class="section-title">操作记录</h3>
        <el-timeline>
          <el-timeline-item
            v-for="record in operationRecords"
            :key="record.id"
            :timestamp="formatDateTime(record.operateTime)"
            :type="getOperationTag(record.operationType)"
          >
            <div class="timeline-content">
              <div class="operation-info">
                <span class="operator">{{ record.operatorName }}</span>
                <span class="operation">{{ getOperationLabel(record.operationType) }}</span>
              </div>
              <div class="operation-comment" v-if="record.comment">
                {{ record.comment }}
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <el-empty description="暂无数据" />
    </div>

    <!-- 底部操作按钮 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button 
          v-if="canApprove" 
          type="primary" 
          @click="handleApprove"
        >
          审批
        </el-button>
        <el-button 
          v-if="canAllocate" 
          type="success" 
          @click="handleAllocate"
        >
          分配教室
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  getStatusLabel, 
  getStatusTag, 
  getApplicationTypeLabel, 
  getApplicationTypeTag, 
  getClassroomTypeLabel,
  getOperationLabel,
  getOperationTag
} from '@/utils/statusMap'
import dayjs from 'dayjs'

// 定义类型
interface ApplicationData {
  applicationId: number
  userName: string
  applicationType: string
  classroomType: string
  expectedPeople: number
  applyDate: string
  startTime: string
  endTime: string
  purpose: string
  equipmentNeeds: string
  status: string
  createTime: string
  approverName?: string
  approveTime?: string
  approveComment?: string
  allocatorName?: string
  allocateTime?: string
}

interface OperationRecord {
  id: number
  operatorName: string
  operationType: string
  operateTime: string
  comment?: string
}

interface AllocatedClassroom {
  classroomCode: string
  capacity: number
  equipment: string
  location: string
}

// Props
interface Props {
  modelValue: boolean
  applicationId?: number
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  applicationId: undefined
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'approve': [applicationId: number]
  'allocate': [applicationId: number]
}>()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const applicationData = ref<ApplicationData | null>(null)
const operationRecords = ref<OperationRecord[]>([])
const allocatedClassrooms = ref<AllocatedClassroom[]>([])

// 计算属性
const equipmentList = computed(() => {
  if (!applicationData.value?.equipmentNeeds) return []
  return applicationData.value.equipmentNeeds.split(',').filter(item => item.trim())
})

const canApprove = computed(() => {
  return applicationData.value?.status === 'PENDING'
})

const canAllocate = computed(() => {
  return applicationData.value?.status === 'APPROVED'
})

// 监听申请ID变化
watch(() => props.applicationId, (newId) => {
  if (newId && visible.value) {
    fetchApplicationDetail(newId)
  }
})

// 监听抽屉显示状态
watch(visible, (newVisible) => {
  if (newVisible && props.applicationId) {
    fetchApplicationDetail(props.applicationId)
  }
})

// 获取申请详情
async function fetchApplicationDetail(applicationId: number) {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    applicationData.value = {
      applicationId: 1001,
      userName: '张老师',
      applicationType: 'TEACHING',
      classroomType: 'MULTIMEDIA',
      expectedPeople: 45,
      applyDate: '2024-01-15',
      startTime: '08:00',
      endTime: '09:40',
      purpose: '计算机基础课程教学，需要多媒体设备进行演示',
      equipmentNeeds: '投影仪,电脑,音响',
      status: 'APPROVED',
      createTime: '2024-01-14 14:30:00',
      approverName: '李管理员',
      approveTime: '2024-01-14 16:20:00',
      approveComment: '申请合理，同意审批',
      allocatorName: '王分配员',
      allocateTime: '2024-01-14 17:15:00'
    }
    
    // 获取操作记录
    fetchOperationRecords(applicationId)
    
    // 获取分配的教室
    if (applicationData.value.status === 'ALLOCATED' || applicationData.value.status === 'COMPLETED') {
      fetchAllocatedClassrooms(applicationId)
    }
  } catch (error) {
    ElMessage.error('获取申请详情失败')
  }
}

// 获取操作记录
async function fetchOperationRecords(applicationId: number) {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    
    operationRecords.value = [
      {
        id: 1,
        operatorName: '张老师',
        operationType: 'SUBMIT',
        operateTime: '2024-01-14 14:30:00',
        comment: '提交申请'
      },
      {
        id: 2,
        operatorName: '李管理员',
        operationType: 'APPROVE',
        operateTime: '2024-01-14 16:20:00',
        comment: '申请合理，同意审批'
      },
      {
        id: 3,
        operatorName: '王分配员',
        operationType: 'ALLOCATE',
        operateTime: '2024-01-14 17:15:00',
        comment: '分配教室A101'
      }
    ]
  } catch (error) {
    ElMessage.error('获取操作记录失败')
  }
}

// 获取分配的教室
async function fetchAllocatedClassrooms(applicationId: number) {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 200))
    
    allocatedClassrooms.value = [
      {
        classroomCode: 'A101',
        capacity: 50,
        equipment: '投影仪,电脑,音响',
        location: 'A楼1层'
      }
    ]
  } catch (error) {
    ElMessage.error('获取分配教室失败')
  }
}

// 审批操作
function handleApprove() {
  if (!applicationData.value) return
  emit('approve', applicationData.value.applicationId)
}

// 分配操作
function handleAllocate() {
  if (!applicationData.value) return
  emit('allocate', applicationData.value.applicationId)
}

function formatDate(date: string) {
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}

function formatDateTime(dateTime: string) {
  return dateTime ? dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss') : ''
}
</script>

<style scoped>
.detail-content {
  padding: 0 20px;
}

.section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.allocated-classrooms {
  margin-top: 16px;
}

.allocated-classrooms h4 {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.timeline-content {
  padding: 8px 0;
}

.operation-info {
  margin-bottom: 4px;
}

.operator {
  font-weight: 500;
  color: #409EFF;
  margin-right: 8px;
}

.operation {
  color: #303133;
}

.operation-comment {
  font-size: 13px;
  color: #909399;
  background: #f8f9fa;
  padding: 8px 12px;
  border-radius: 4px;
  margin-top: 8px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 